﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Content;

namespace Dynamo
{
    public partial class DynamoSettings : DotNetNuke.Entities.Modules.PortalModuleBase
    {
        
        List<Script> scripts = new List<Script>();
        DNNJintEngine engine;
        protected void Page_Load(object sender, EventArgs e)
        {
            PagePanel.Visible = Dynamo.AdminPermissions.ScriptingEnabled;
            DisabledPanel.Visible = !Dynamo.AdminPermissions.ScriptingEnabled;

            if (Dynamo.AdminPermissions.ScriptingEnabled)
            {
                Page.ClientScript.RegisterClientScriptInclude("EditArea", ResolveClientUrl("~/DesktopModules/Dynamo/edit_area/edit_area_full.js"));
                engine = new DNNJintEngine(this.Panel1, this.Page, this);
                engine.Debug = true;

                engine.JintEngine.Step += new EventHandler<Jint.Debugger.DebugInformation>(JintEngine_Step);
                engine.JintEngine.Break += new EventHandler<Jint.Debugger.DebugInformation>(JintEngine_Break);

                if (!Page.IsPostBack)
                {
                    string script =  Dynamo.AdminPermissions.LoadScript(TabId, ModuleId);

                    if (string.IsNullOrEmpty(script)) script = "@{return \"Hello World\";}@";
                    TextBox1.Text = script;
                    if (scripts.Count <= 0)
                    {
                        string root = Server.MapPath("~/DesktopModules/Dynamo/Scripts/");
                        foreach (string file in System.IO.Directory.GetFiles(root, "*.js", System.IO.SearchOption.AllDirectories))
                        {
                            Script s = new Script(file);
                            scripts.Add(s);
                            ScriptsDDL.Items.Add(new ListItem(s.DisplayName, s.Path));
                        }
                    }
                }
            }
        }

        void JintEngine_Break(object sender, Jint.Debugger.DebugInformation e)
        {
            this.DebuggerPanel.Controls.Add(new LiteralControl("<br /><hr width='100%'><br />Break:"));
            string DebugInfo = EmitDebugInformation(e);
            this.DebuggerPanel.Controls.Add(new LiteralControl(DebugInfo));
            this.DebuggerPanel.Controls.Add(new LiteralControl("<br /><hr width='100%'><br />Done Break"));
        }

        void JintEngine_Step(object sender, Jint.Debugger.DebugInformation e)
        {
            this.DebuggerPanel.Controls.Add(new LiteralControl("<br /><hr width='100%'><br />Step:"));
            string DebugInfo = EmitDebugInformation(e);
            this.DebuggerPanel.Controls.Add(new LiteralControl(DebugInfo));
            this.DebuggerPanel.Controls.Add(new LiteralControl("<br /><hr width='100%'><br />Done Step"));
        }
        private string EmitDebugInformation(Jint.Debugger.DebugInformation e)
        {
            
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (string stack in e.CallStack)
            {
                sb.Append(stack + "<br />");
            }
            sb.Append("Current Statement: Label:" + e.CurrentStatement.Label + ", Source:" + e.CurrentStatement.Source.Code.Replace(">", "&gt;").Replace("<", "&lt;"));

            sb.Append("Locals:<br />");
            foreach (string key in e.Locals.GetKeys())
            {
                try
                {
                    if((e.Locals[key]).Class!="function")  sb.Append("(" + key + ")=[" + e.Locals[key].ToString().Replace(">","&gt;").Replace("<","&lt;") + "]");
                }
                catch (Exception)
                {
                    sb.Append("(" + key + ")=[N/A]");
                }                
            }
            return sb.ToString().Replace("\n", "<br />");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DebuggerPanel.Visible = ShowDebuggerDetailsCheckbox.Checked;
            engine.JintEngine.SetDebugMode(DebuggerPanel.Visible);
            if (TextBox1.Text != null && TextBox1.Text.Trim() != "")
            {
                string result = engine.Run(TextBox1.Text);
                if (result != null)
                {
                    this.Panel1.Controls.Add(new LiteralControl(result.Replace("\n", "<br />")));
                }
            }
        }

        DotNetNuke.Entities.Modules.ModuleController controller = new DotNetNuke.Entities.Modules.ModuleController();

        protected void SaveButton_Click(object sender, EventArgs e)
        {

            string script = TextBox1.Text;

            Dynamo.AdminPermissions.SaveScript(script, TabId, ModuleId);

           Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
        }

        protected void UseSampleButton_Click(object sender, EventArgs e)
        {
            Script s = new Script(ScriptsDDL.SelectedValue);
            TextBox1.Text = s.Source;
        }

    }
}